//
//  AppDelegate.m
//  CurbApp
//
//  Created by LH on 16/6/20.
//  Copyright © 2016年 LH. All rights reserved.
//

#import "AppDelegate.h"
#import "RSASignVerify.h"
#import "SecurityUtil.h"
#import "LHNetWorking.h"
@interface AppDelegate ()
@property (nonatomic,copy)NSString *secretKey;
@end

@implementation AppDelegate

#pragma mark 验证安装
-(void)installationVerification{
    //字符串公钥加密  返回十六进制字符串
    NSString *secretKey16Str= [self encryptRSAString:self.secretKey];
    //设备信息json字符串
    NSString *deviceInfo=[self deviceBasicInformation];
    //设备信息AES加密十六进制字符串
    NSString *deviceInfo16Str=[self AES128Encrypt:deviceInfo key:self.secretKey];
    [LHNetWorking getDownloadValidation:@{@"key":secretKey16Str,@"text":deviceInfo16Str} whileSuccess:^(id reponsObject) {
        NSDictionary *reponsDic=reponsObject;
        NSString *token=reponsObject[@"token"];
        //tid保存到本地
        [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"tid"];
        
    } orFail:^(id responsObject) {
        
    }];
    
    
    
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSString *key=[[NSUserDefaults standardUserDefaults] valueForKey:@"secretKey"];
    if(!key){
        //生成16位随机key
        self.secretKey=[self randomSixteenString];
        //secretKey保存到本地
        [[NSUserDefaults standardUserDefaults] setObject:self.secretKey forKey:@"secretKey"];
         // [[NSUserDefaults standardUserDefaults] setObject:@"12245548754" forKey:@"tid"];
        if (self.secretKey) {
           [self installationVerification];
        }
        
    }else{
        self.secretKey=key;
    }
    
    return YES;
}

/**
 * 设置设备基本信息
 */
-(NSString *)deviceBasicInformation{
    
    NSString *version= [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];//获取版本号
    UIDevice *device = [[UIDevice alloc]init];
    NSString *name = device.name;       //获取设备所有者的名称
    NSString *model = device.name;      //获取设备的类别
    NSString *type = device.localizedModel; //获取本地化版本
    NSString *systemName = device.systemName;   //获取当前运行的系统
    NSString *systemVersion = device.systemVersion;//获取当前系统的版本
    //获取设备的唯一标示符
    NSString *identifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    
    NSMutableDictionary *deviceDic=[[NSMutableDictionary alloc]init];
    [deviceDic setValue:version forKey:@"app_version"];//软件版本
    [deviceDic setValue:identifier forKey:@"deviceMac"];//设备唯一码
    [deviceDic setValue:@"iOS" forKey:@"deviceType"];//设备类型
    [deviceDic setValue:@"Apple" forKey:@"deviceBrand"];//设备品牌
    [deviceDic setValue:self.secretKey forKey:@"secret"];//16位随机KEY
    
    return [self dictionaryToJson:deviceDic];
}
/**
 * 十六位随机码 十位数字加五位数字 不能重复
 */
-(NSString *)randomSixteenString{
    NSString *string = [[NSString alloc]init];
    //随机数从这里边产生
    NSMutableArray *startArray=[[NSMutableArray alloc] initWithObjects:@0,@1,@2,@3,@4,@5,@6,@7,@8,@9, nil];
    //随机数产生结果
    NSMutableArray *resultArray=[[NSMutableArray alloc] initWithCapacity:0];
    //随机数个数
    NSInteger m=10;
    for (int i=0; i<m; i++) {
        int t=arc4random()%startArray.count;
        resultArray[i]=startArray[t];
        
        startArray[t]=[startArray lastObject]; //为更好的乱序，故交换下位置
        [startArray removeLastObject];
    }
    for (int i=0; i<resultArray.count; i++) {
        NSString *tempString = [NSString stringWithFormat:@"%@",resultArray[i]];
        string = [string stringByAppendingString:tempString];
    }
    NSString *shuffStr=  [self shuffledAlphabet];
    string = [string stringByAppendingString:shuffStr];
    NSLog(@"十六位随机数:%@",string);
    return string;
}
/**
 * 六个随机字母
 */
- (NSString *)shuffledAlphabet {
    NSString *alphabet = @"abcdefghijklmnopqrstuvwsyz";
    // 把字符转换为有效的洗牌
    NSUInteger numberOfCharacters = [alphabet length];
    unichar *characters = calloc(numberOfCharacters, sizeof(unichar));
    [alphabet getCharacters:characters range:NSMakeRange(0, numberOfCharacters)];
    for (NSUInteger i = 0; i < 6; ++i) {
        NSUInteger j = (arc4random_uniform(numberOfCharacters - i) + i);
        unichar c = characters[i];
        characters[i] = characters[j];
        characters[j] = c;
    }
    // 把结果变成一个字符串
    NSString *result = [NSString stringWithCharacters:characters length:6];
    free(characters);
    return result;
}
//字典转json字符串
-(NSString*)dictionaryToJson:(NSMutableDictionary *)dic

{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
#pragma mark RSA加密
/**
 * RSA加密
 * 返回:加密十六进制字符串
 */
-(NSString *)encryptRSAString:(NSString *)secretKey{
    NSString *pubkey=@"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDSD49Z9gDtnyRphqSLrCZuY5kLEnPZKdokdBVSuDfPoCOM+870w7cWr/lfQArWlgMH26+B0wRpk+sPI4W0XCeW4qGLtk16aPgDWFEAwMseHX9neHaNDzzeAFPvbzpzQ8dUZFZ1D1ECSCX7fgxdhApLpCZMYCZMcsB4z4VPanFLbQIDAQAB";
    RSASignVerify* handler = [RSASignVerify sharedInstance];
    [handler importKeyWithType:KeyTypePublic andkeyString:pubkey];
    NSData* resultData = [handler encryptWithPublicKey:secretKey];
    NSString* str=[self convertDataToHexStr:resultData];
    return str;
}
/**
 * 将NSData转换成十六进制的字符串
 */
- (NSString *)convertDataToHexStr:(NSData *)data {
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    
    return string;
}
#pragma mark AES加密
-(NSString *)AES128Encrypt:(NSString *)plainText key:(NSString *)key{

    NSString * hexString = [SecurityUtil encryptAESDataToHexString:plainText app_key:key];
    NSLog(@"%@",[NSString stringWithFormat:@"加密key:%@",key]);
    NSLog(@"%@",[NSString stringWithFormat:@"加密前:%@",plainText]);
    NSLog(@"%@",[NSString stringWithFormat:@"加密后16进制:%@",hexString]);
    return hexString;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
